package com.example.media.slice;

import com.example.media.ResourceTable;
import com.example.media.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;

public class MediaAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Button mBtnVideoMedia;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_media);
        mBtnVideoMedia = (Button) findComponentById(ResourceTable.Id_btn_video_media);
        mBtnVideoMedia.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {

        // DataAbilityHelper对象
        DataAbilityHelper helper = DataAbilityHelper.creator(this);
        // 结果集
        ResultSet rs = null;
        try {
            // 查找文件
            rs = helper.query(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI,
                    new String[]{AVStorage.Video.Media.ID}, null);
            Utils.log("查询视频文件数量:" + rs.getRowCount());
            // 遍历被查找的文件
            while (rs != null && rs.goToNextRow()) {
                // 获得Media ID
                int mediaId = rs.getInt(0);
                // 构建URI对象
                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI, "" + mediaId);
                Utils.log("文件URL : " + uri.toString());
                // 打开文件
                FileDescriptor fileDescriptor = helper.openFile(uri, "r");
                // 操作文件
                // new FileReader(fileDescriptor);
            }
        } catch (Exception e) {
            Utils.log(e.getLocalizedMessage());
        } finally {
            if (rs != null) rs.close();
        }
    }
}
